package com.bnq.control.desktop;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bnq.control.R;
import com.bnq.control.common.constant.CNTS;
import com.bnq.control.common.dialog.LoadingDialog;
import com.bnq.control.common.utils.ConnectStatus;
import com.bnq.control.common.utils.NetWorkUtils;
import com.bnq.control.common.utils.PermissionUtils;
import com.bnq.control.common.utils.ToastUtils;
import com.bnq.control.desktop.utils.BluetoothUtils;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.oray.sunlogin.bean.PluginParam;
import com.oray.sunlogin.manager.DesktopPluginManager;
import com.oray.sunlogin.plugin.JavaPlugin;

import org.json.JSONException;
import org.json.JSONObject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

/**
 * 桌面插件
 */
public class DesktopActivity extends AppCompatActivity {

    private static final int REQUESTCODE_PERMISSION = 1;
    private static final int REQUESTCODE_QRCODE = 2;

    private boolean isAndroid;

    // 调用插件所需要的类
    private DesktopPluginManager mDesktopManager;
    // 插件连接的监听
    private JavaPlugin.IConnectorListener connectorListener;

    private TextView textConnectStatus;
    private View btnQRCode, btnConnectDesktop, btnDisconnectDesktop, btnConnectAndroidDesktop;
    private View btnCleanDesktopAddress, btnCleanSoundAddress, btnCleanDesktopSession, btnCleanVoiceSession;
    private EditText textP2PAddress, textSoundP2PAddress, textDesktopSession, textSoundSession;
    private CheckBox cbSoftMediaCodec;
    private LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.plugin_desktop_view);

        initView();

        getApplication().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
                System.out.println("---------------onActivityCreated:"+activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                System.out.println("---------------onActivityStarted:"+activity);
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                System.out.println("---------------onActivityResumed:"+activity);
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                System.out.println("---------------onActivityPaused:"+activity);
            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                System.out.println("---------------onActivityStopped:"+activity);
            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {
                System.out.println("---------------onActivitySaveInstanceState:"+activity);
            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                System.out.println("---------------onActivityDestroyed:"+activity);
            }
        });
    }

    private void initView() {
        mDesktopManager = DesktopPluginManager.getInstance();
        mDesktopManager.resetDesktopIndex();

        btnQRCode = findViewById(R.id.button_qrcode);
        textP2PAddress = findViewById(R.id.text_p2p_address);

        textSoundP2PAddress = findViewById(R.id.text_p2p_adress2);
        //desktop
        btnCleanDesktopAddress = findViewById(R.id.clean_p2p_address);
        btnCleanSoundAddress = findViewById(R.id.clean_sound_address);

        btnCleanDesktopSession = findViewById(R.id.clean_session_desktop);
        btnCleanVoiceSession = findViewById(R.id.clean_session_voice);

        btnConnectDesktop = findViewById(R.id.button_connect_desktop);
        btnDisconnectDesktop = findViewById(R.id.button_disconnect_desktop);
        btnConnectAndroidDesktop = findViewById(R.id.button_connect_androiddesktop);

        textDesktopSession = findViewById(R.id.text_session_desktop);
        textSoundSession = findViewById(R.id.text_session_sound);

        textConnectStatus = findViewById(R.id.tv_connect_status);
        cbSoftMediaCodec = findViewById(R.id.cb_soft_media_codec);

        initListener();
    }

    private void initListener() {
        btnQRCode.setOnClickListener(v -> {
            if (!PermissionUtils.hasPermission(v.getContext(), Manifest.permission.CAMERA)) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA}, REQUESTCODE_PERMISSION);
            } else {
                //Intent i = new Intent(this, CaptureActivity.class);
                //startActivityForResult(i, REQUESTCODE_QRCODE);
                HmsScanAnalyzerOptions options = new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create();
                ScanUtil.startScan(this, REQUESTCODE_QRCODE, options);
            }
        });

        // 插件连接状态的监听器
        connectorListener = (nStatus, nError) -> {
            String str = ConnectStatus.getConnectStatus(nStatus);
            switch (nStatus) {
                case CNTS.CONNECTED:
                    str = "已连接";
                    Intent intent;
                    if (!isAndroid) {
                        intent = new Intent(DesktopActivity.this, RemoteDesktopActivity.class);
                        String p2pAddress = textP2PAddress.getText().toString();
                        String p2pAddress2 = textSoundP2PAddress.getText().toString();
                        String address_text = TextUtils.isEmpty(p2pAddress2) ? p2pAddress : p2pAddress2;
                        String session_text_sound = textSoundSession.getText().toString();
                        intent.putExtra(RemoteDesktopActivity.SOUND_ADDRESS, address_text);
                        intent.putExtra(RemoteDesktopActivity.SOUND_SESSION, session_text_sound);
                        startActivity(intent);
                    } else {
                        intent = new Intent(DesktopActivity.this, RemoteAndroidActivity.class);
                        startActivity(intent);
                    }


                    cancelLoadingDialog();
                    textDesktopSession.setText("");
                    textSoundP2PAddress.setText("");
                    textSoundSession.setText("");
                    break;
                case CNTS.DISCONNECTED:
                    cancelLoadingDialog();
                    str = "已断开连接";
                    runOnUiThread(this::cancelDesktop);
                    break;
            }
            showConnectStatus(str);
        };
        btnCleanDesktopAddress.setOnClickListener(view -> textP2PAddress.setText(""));
        btnCleanSoundAddress.setOnClickListener(view -> textSoundP2PAddress.setText(""));
        btnCleanDesktopSession.setOnClickListener(view -> textDesktopSession.setText(""));
        btnCleanVoiceSession.setOnClickListener(view -> textSoundSession.setText(""));

        // 连接插件
        btnConnectDesktop.setOnClickListener(v -> {
            isAndroid = false;
            BluetoothUtils.initBluetoothAdapterStatus(this);  // 初始化蓝牙
            connectionRemoteDesktop();
        });
        btnConnectAndroidDesktop.setOnClickListener(v -> {
            isAndroid = true;
            connectionRemoteDesktop();
        });

        btnDisconnectDesktop.setOnClickListener(view -> {
            if (!"已断开".equals(textConnectStatus.getText().toString()) && !"转发连接已断开".equals(textConnectStatus.getText().toString())) {
                cancelDesktop();
                textConnectStatus.setText("已断开");
            }
        });

        cbSoftMediaCodec.setOnCheckedChangeListener((buttonView, isChecked) -> mDesktopManager.setSoftMediaCodec(isChecked));
    }

    private void showConnectStatus(String str) {
        runOnUiThread(() -> textConnectStatus.setText(str));
    }

    private void showToastText(String str) {
        runOnUiThread(() -> Toast.makeText(this, str, Toast.LENGTH_SHORT).show());
    }

    /**
     * 断开远程桌面
     */
    private void cancelDesktop() {
        if (null != mDesktopManager) {
            mDesktopManager.cancelPlugin();
            mDesktopManager.removeConnectorListener(connectorListener);
            textConnectStatus.setText("连接已经断开");
            mDesktopManager.clearDesktopPlugin();
            mDesktopManager.resetDesktopIndex();
        }
    }

    /**
     * 连接远程桌面
     */
    private void connectionRemoteDesktop() {
        String address_text = textP2PAddress.getText().toString();
        String session_desktop = textDesktopSession.getText().toString();
        if (!NetWorkUtils.hasActiveNet(getApplicationContext())) {
            showToastText("请检查网络连接状况");
        } else if (!TextUtils.isEmpty(session_desktop) && !TextUtils.isEmpty(address_text)) {
            showLoadingDialog();
            mDesktopManager.addConnectorListener(connectorListener);
            PluginParam param = new PluginParam();
            param.setAddress(address_text);
            param.setSession(session_desktop);
            mDesktopManager.connectPlugin(param);
        } else {
            showToastText("登录地址或者桌面会话地址为空");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUESTCODE_PERMISSION) {
            if (PermissionUtils.hasPermission(this, Manifest.permission.CAMERA)) {
                //Intent i = new Intent(this, CaptureActivity.class);
                //startActivityForResult(i, REQUESTCODE_QRCODE);
                //ToastUtils.showSingleToast("扫码添加",this);
                // “QRCODE_SCAN_TYPE”和“DATAMATRIX_SCAN_TYPE”表示只扫描QR和Data Matrix的码
                HmsScanAnalyzerOptions options = new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create();
                ScanUtil.startScan(this, REQUESTCODE_QRCODE, options);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_QRCODE) {
            if (resultCode == RESULT_OK) {
                //String result = data.getStringExtra("result");
                HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
                String result = obj.getOriginalValue();
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(result);
                    String address = jsonObject.isNull("address") ? "" : jsonObject.getString("address");
                    String desktop = jsonObject.isNull("desktop") ? "" : jsonObject.getString("desktop");
                    String sound = jsonObject.isNull("sound") ? "" : jsonObject.getString("sound");
                    textP2PAddress.setText(address);
                    textDesktopSession.setText(desktop);
                    textSoundSession.setText(sound);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean isConnectedBluetoothKeyboard() {
        return BluetoothUtils.isConnectedBluetoothKeyboard;
    }

    private void showLoadingDialog() {
        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.setOnTimeoutListener(() -> {
            if (null != mLoadingDialog) mLoadingDialog.dismiss();
            cancelDesktop();
        });
        mLoadingDialog.setTimeOut(10 * 1000);
        mLoadingDialog.setTips("连接中...");
        mLoadingDialog.show();
    }

    private void cancelLoadingDialog() {
        if (null != mLoadingDialog)
            mLoadingDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelDesktop();
        cancelLoadingDialog();
    }
}
